package case14

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"study_gorm_v2/src/case13"
	"time"
)

func Test() {
	fmt.Println("🎯示例十四：查询错误处理")

	db, err := mysqlConnect()
	if err != nil {
		fmt.Println(err)
		return
	}

	// 单条查询
	var u1 case13.UserCase13
	result := db.First(&u1, "id = ?", 1)
	if result.Error != nil {
		fmt.Println("未查询到：", result.Error)
		return
	}
	fmt.Println(u1)

	// 列表查询
	var uArr1 []case13.UserCase13
	if result := db.Find(&uArr1, "id = ?", 11); result.RowsAffected == 0 {
		fmt.Println("未查询到数据：ID 11 不存在")
		return
	}
	fmt.Println(uArr1)
	fmt.Println(db)
}

// 初始化连接
func mysqlConnect() (*gorm.DB, error) {
	url := "root:123456@tcp(127.0.0.1:3306)/case1?charset=utf8mb4&parseTime=True&loc=Local"

	// 配置自定义 Logger 打印sql日志
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second, // 慢 SQL 阈值
			LogLevel:                  logger.Info, // 可以设置为不同级别 Silent-不打印任何日志 Error-只打印错误日志 Warn-打印慢查询和错误 Info-打印慢查询和错误
			IgnoreRecordNotFoundError: true,        // 忽略ErrRecordNotFound（记录未找到）错误
			Colorful:                  true,        // 彩色打印
		},
	)

	db, err := gorm.Open(mysql.Open(url), &gorm.Config{
		Logger: newLogger, // 设置 Logger
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 关闭默认，使用表名
		},
	})
	if err != nil {
		return nil, fmt.Errorf("mysql connect err: %v", err)
	}

	return db, nil
}
